package com.laich.springcloud.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.laich.springcloud.dao.SysUserDao;
import com.laich.springcloud.entity.SysPermission;
import com.laich.springcloud.entity.SysUser;
import com.laich.springcloud.security.MyUser;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class UserService implements UserDetailsService {

	private static final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

	@Autowired
	private SysUserDao userDao;
	@Autowired
	private PermissionService permissionService;
	@Autowired
	private PasswordEncoder passwordEncoder;

	public SysUser create(String username, String password) {
		SysUser user = new SysUser();
		user.setUsername(username);
		String hash = encoder.encode(password);
		user.setPassword(hash);
		SysUser u = userDao.save(user);
		return u;

	}

	public SysUser findByUsername(String username) {
		return userDao.findByUsername(username);
	}

	/**
	 * Security 登录身份证认证
	 */
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		SysUser sysUser = userDao.findByUsername(username);
		if (sysUser == null) {
			log.info("登录用户【" + username + "】不存在.");
			throw new UsernameNotFoundException("登录用户【" + username + "】不存在.");
		}

		List<SysPermission> permissionList = permissionService.findByUserId(sysUser.getId());
		List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
		if (!CollectionUtils.isEmpty(permissionList)) {
			for (SysPermission sysPermission : permissionList) {
				authorityList.add(new SimpleGrantedAuthority(sysPermission.getCode()));
			}
		}

		MyUser myUser = new MyUser(sysUser.getUsername(), passwordEncoder.encode(sysUser.getPassword()), authorityList);

		log.info("登录成功！用户: {}", JSON.toJSONString(myUser));

		return myUser;
	}

	/**
	 * 模拟一个角色
	 */
	private List getAuthority() {
		return Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN"));
	}

	public SysUser getUser(String id) {
		long userId = Long.parseLong(id);
		SysUser user = userDao.findById(userId).get();
		return user;
	}
}
